package Orm.jdbc.connectorPool;

import javax.sql.DataSource;
import java.io.BufferedReader;
import java.io.FileReader;
import java.sql.Connection;
import java.sql.DriverManager;

public class JDBCUtils {

    public static DataSource dataSource;
    public static String username;
    public static String password;

    static {
        //驱动加载
        try{
            Class.forName("com.mysql.cj.jdbc.Driver");
            System.out.println("成功mysql加载驱动！！");
            FileReader file = new FileReader("Java动手做一做/src/main/resources/database");
            BufferedReader bufferedReader = new BufferedReader(file);
            String first = bufferedReader.readLine();
            String second = bufferedReader.readLine();
            if(first.contains("username")){
                String[] u = first.split("=");
                username = u[1];
            }
            if(second.contains("password")){
                password = second.split("=")[1];
            }
            System.out.println("数据库账户密码读取完毕");
            dataSource = new MyDataSource();
            System.out.println("数据源准备完毕！！");
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public static Connection getConnection(){
        //和数据库建立连接
        String url="jdbc:mysql://localhost:3306/world?&useSSL=false&serverTimezone=UTC&generateSimpleParameterMetadata=true";
        try {
            Connection conn = DriverManager.getConnection(url,username,password);
            //System.out.println("成功获取数据库连接！！");
            return conn;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    public static Connection getConnection(String username,String password){
        //和数据库建立连接
        String url="jdbc:mysql://localhost:3306/world?&useSSL=false&serverTimezone=UTC";
        try {
            Connection conn = DriverManager.getConnection(url,username,password);
            System.out.println("成功获取数据库连接！！");
            return conn;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
}
